<template>
  <common-header/>

  <div class="gym-container">    <!-- 分类标签页 -->
    <n-tabs type="line" animated class="gym-tabs" v-model:value="currentCategory">
      <n-tab-pane name="all" tab="全部" />
      <n-tab-pane name="健身房" tab="健身房" />
      <n-tab-pane name="瑜伽馆" tab="瑜伽馆" />
      <n-tab-pane name="游泳馆" tab="游泳馆" />
      <n-tab-pane name="私教工作室" tab="私教工作室" />
      <n-tab-pane name="拳击馆" tab="拳击馆" />
    </n-tabs>

    <!-- 场馆卡片网格 -->
    <div class="gym-grid" v-if="filteredGyms.length > 0">
      <n-card
          v-for="gym in filteredGyms"
          :key="gym.id"
          class="gym-card"
          hoverable
          @click="handleGymClick(gym)"
      >
        <!-- 场馆图片 -->
        <div class="gym-image-container">
          <n-image
              v-if="gym.photos && gym.photos.length > 0"
              :src="gym.photos[0].url"
              class="gym-image"
              preview-disabled
              object-fit="cover"
              :alt="gym.name"
          />
          <div v-else class="no-image">
            <n-icon size="48" color="#ccc">
              <LocationOutline />
            </n-icon>
            <n-text depth="3">暂无图片</n-text>
          </div>

          <!-- 评分标签 -->
          <n-tag
              v-if="gym.rating"
              class="rating-tag"
              type="warning"
              size="small"
              round
          >
            <template #icon>
              <n-icon><Star /></n-icon>
            </template>
            {{ gym.rating }}
          </n-tag>
        </div>        <!-- 场馆信息 -->
        <n-space vertical :size="8" class="gym-info">
          <n-text strong class="gym-name">{{ gym.name }}</n-text>

          <n-flex justify="space-between" align="center">
            <n-tag :bordered="false" type="info" size="small">
              {{ getGymCategory(gym.type) }}
            </n-tag>
            <n-text depth="3" size="small">{{ gym.distance }}m</n-text>
          </n-flex>

          <!-- 认领状态标签 -->
          <n-flex justify="space-between" align="center" v-if="isGymClaimed(gym)">
            <n-tag :type="getStatusType(gym.status)" size="small">
              {{ getStatusText(gym.status) }}
            </n-tag>
            <n-text depth="3" size="small" v-if="gym.opening_hours">
              {{ gym.opening_hours }}
            </n-text>
          </n-flex>

          <n-text depth="2" size="small" class="gym-address">
            <n-icon size="14"><LocationOutline /></n-icon>
            {{ gym.address }}
          </n-text>

          <n-text depth="2" size="small" v-if="gym.tel">
            <n-icon size="14"><Call /></n-icon>
            {{ gym.tel }}
          </n-text>

          <!-- 认领员工信息预览 -->
          <n-flex align="center" :size="8" v-if="gym.claimedStaff" class="staff-preview">
            <n-avatar
                :size="20"
                :src="gym.claimedStaff.avatar"
                :fallback-src="'/default_avatar.svg'"
                round
            />
            <n-text depth="3" size="small">
              管理员: {{ gym.claimedStaff.nickname || gym.claimedStaff.username }}
            </n-text>
          </n-flex>
        </n-space>
      </n-card>
    </div>

    <!-- 空状态 -->
    <n-empty v-else description="暂无健身场馆数据" class="empty-state">
      <template #extra>
        <n-button @click="handleGoToMap">
          <template #icon>
            <n-icon><LocationOutline /></n-icon>
          </template>
          去地图搜索附近场馆
        </n-button>
      </template>
    </n-empty>

    <!-- 健身场馆详情弹窗 -->
    <n-modal
        v-model:show="showDetailModal"
        preset="card"
        class="gym-detail-modal"
        :style="{ width: '80%', maxWidth: '1000px' }"
        title="健身场馆详情"
        :mask-closable="false"
    >
      <n-scrollbar style="max-height: 70vh;">
        <div v-if="currentGym" class="gym-detail">
          <!-- 场馆基本信息 -->
          <n-space vertical :size="20">
            <!-- 场馆头部信息 -->
            <div class="gym-header">
              <n-flex justify="space-between" align="flex-start">
                <n-space vertical :size="12">
                  <n-h2>{{ currentGym.name }}</n-h2>
                  <n-space align="center" :size="16">
                    <n-tag type="info">{{ getGymCategory(currentGym.type) }}</n-tag>
                    <n-text v-if="currentGym.rating" depth="2">
                      <n-icon color="#fadb14"><Star /></n-icon>
                      评分: {{ currentGym.rating }}
                    </n-text>
                    <n-text depth="2">距离: {{ currentGym.distance }}m</n-text>
                  </n-space>
                </n-space>                <n-button type="primary" @click="handleCallGym" v-if="currentGym.tel">
                <template #icon>
                  <n-icon><Call /></n-icon>
                </template>
                联系场馆
              </n-button>
              </n-flex>
            </div>

            <!-- 场馆图片轮播 -->
            <div v-if="currentGym.photos && currentGym.photos.length > 0" class="gym-photos">
              <n-h3>场馆风貌</n-h3>
              <n-carousel autoplay dot-type="line">
                <img
                    v-for="(photo, index) in currentGym.photos"
                    :key="index"
                    :src="photo.url"
                    class="carousel-image"
                    :alt="photo.title || currentGym.name"
                />
              </n-carousel>
            </div>

            <!-- 联系信息 -->
            <div class="contact-info">
              <n-h3>联系信息</n-h3>
              <n-descriptions :column="2" bordered>
                <n-descriptions-item label="地址">
                  <n-text>{{ currentGym.address }}</n-text>
                </n-descriptions-item>
                <n-descriptions-item label="电话" v-if="currentGym.tel">
                  <n-text>{{ currentGym.tel }}</n-text>
                </n-descriptions-item>
                <n-descriptions-item label="所属区域">
                  <n-text>{{ currentGym.adname }}</n-text>
                </n-descriptions-item>                <n-descriptions-item label="营业时间">
                <n-text>{{ currentGym.business_hours || '10:00-22:00' }}</n-text>
              </n-descriptions-item>
              </n-descriptions>            </div>            <!-- 场馆认领 -->
            <div v-if="!isGymClaimed(currentGym)" class="gym-claim-section">
              <n-h3>场馆认领</n-h3>
              <n-alert type="info" style="margin-bottom: 16px;">
                这是来自POI数据的场馆信息，如果您是场馆经营者，可以认领此场馆并管理相关信息。
              </n-alert>
              <n-button
                  type="primary"
                  size="large"
                  @click="openClaimModal"
                  :disabled="!isGymStaff"
                  style="font-size: 16px; padding: 12px 24px;"
              >
                <template #icon>
                  <n-icon><BusinessOutline /></n-icon>
                </template>
                认领此场馆
              </n-button>
              <n-text v-if="!isGymStaff" depth="3" size="small" style="margin-top: 8px; display: block;">
                需要场馆人员身份才能认领场馆
              </n-text>
            </div>            <div v-else class="gym-claimed-section">
            <n-h3>场馆管理信息</n-h3>              <n-alert type="success" style="margin-bottom: 16px;">
            <template #icon>
              <n-icon><BusinessOutline /></n-icon>
            </template>
            该场馆已被认领，当前状态为{{ getStatusText(currentGym.status) }}
          </n-alert>

            <!-- 为场馆所有者显示特殊提示 -->
            <n-alert
                v-if="isGymOwner(currentGym)"
                type="info"
                style="margin-bottom: 16px;"
                title="场馆管理提示"
            >
              <template #icon>
                <n-icon><Settings /></n-icon>
              </template>
              您是这个场馆的管理员，可以前往管理中心设置营业状态、编辑场馆信息和管理预约。
              <template #action>
                <n-button size="small" type="primary" @click="goToManagementCenter">
                  <template #icon>
                    <n-icon><BusinessOutline /></n-icon>
                  </template>
                  进入管理中心
                </n-button>
              </template>
            </n-alert>

            <!-- 认领员工信息 -->
            <n-card v-if="currentGym.claimedStaff" size="small" class="staff-info-card">
              <template #header>
                <n-flex align="center" :size="8">
                  <n-icon><PersonOutline /></n-icon>
                  <span>场馆管理员</span>
                </n-flex>
              </template>
              <n-flex align="center" :size="12">
                <n-avatar
                    :size="48"
                    :src="currentGym.claimedStaff.avatar"
                    :fallback-src="'/default_avatar.svg'"
                    round
                />
                <n-space vertical :size="4">
                  <n-text strong>{{ currentGym.claimedStaff.nickname || currentGym.claimedStaff.username }}</n-text>
                  <n-text depth="3" size="small">认领时间: {{ formatDate(currentGym.claimedAt) }}</n-text>
                  <n-flex align="center" :size="8">
                    <n-tag :type="getStatusType(currentGym.status)" size="small">
                      {{ getStatusText(currentGym.status) }}
                    </n-tag>
                    <n-text depth="3" size="small" v-if="currentGym.opening_hours">
                      营业时间: {{ currentGym.opening_hours }}
                    </n-text>
                  </n-flex>
                </n-space>
              </n-flex>
            </n-card>
          </div>

            <!-- 器械设施 -->
            <div class="gym-equipments">
              <n-h3>器械设施</n-h3>
              <div v-if="currentGymEquipments.length > 0">
                <n-grid :cols="2" :x-gap="12" :y-gap="12">
                  <n-grid-item v-for="equipment in currentGymEquipments" :key="equipment.id">
                    <n-card size="small" hoverable>
                      <template #header>
                        <n-space justify="space-between" align="center">
                          <n-text strong>{{ equipment.name }}</n-text>
                          <n-tag
                              :type="equipment.status === '可用' ? 'success' : equipment.status === '维护中' ? 'warning' : 'error'"
                              size="small"
                          >
                            {{ equipment.status }}
                          </n-tag>
                        </n-space>
                      </template>
                      <n-space vertical :size="8">
                        <n-text depth="2" size="small">{{ equipment.description }}</n-text>
                        <n-flex justify="space-between" align="center">
                          <n-text depth="3" size="small">{{ equipment.brand }}</n-text>
                          <n-text depth="3" size="small">使用量: {{ equipment.usageCount }}次</n-text>
                        </n-flex>
                      </n-space>
                    </n-card>
                  </n-grid-item>
                </n-grid>
              </div>
              <n-empty v-else size="small" description="暂无器械信息">
                <template #extra>
                  <n-text depth="3" size="small">
                    建议致电场馆咨询具体器械设施情况
                  </n-text>
                </template>
              </n-empty>
            </div>            <!-- 预约时段 - 只有非场馆人员才显示 -->
            <div v-if="!isGymStaff" class="reservation-section">
              <n-flex justify="space-between" align="center" class="section-header">
                <n-h3>预约时段</n-h3>
                <n-button type="primary" @click="handleReservation">
                  <template #icon>
                    <n-icon><Calendar /></n-icon>
                  </template>
                  立即预约
                </n-button>
              </n-flex>
              <n-alert type="info" style="margin-bottom: 16px;" size="small">
                点击"立即预约"按钮可查看实时可用时间段并进行预约
              </n-alert>
            </div>

            <!-- 场馆介绍 -->
            <div class="gym-description">
              <n-h3>场馆介绍</n-h3>
              <n-text>{{ currentGym.description || '暂无详细介绍' }}</n-text>
            </div>
          </n-space>
        </div>
      </n-scrollbar>      <template #action>
      <n-space justify="end">
        <n-button @click="showDetailModal = false">关闭</n-button>
        <n-button v-if="!isGymStaff" type="primary" @click="handleReservation">立即预约</n-button>
      </n-space>
    </template>
    </n-modal>    <!-- 预约弹窗 -->
    <n-modal
        v-model:show="showReservationModal"
        preset="card"
        class="reservation-modal"
        title="场馆预约"
        style="width: 700px;"
        :mask-closable="false"
    >
      <n-scrollbar style="max-height: 70vh;">
        <n-space vertical :size="20">
          <!-- 当前场馆信息 -->
          <n-card size="small" v-if="currentGym">
            <template #header>
              <n-flex align="center" :size="8">
                <n-icon><LocationOutline /></n-icon>
                <span>预约场馆</span>
              </n-flex>
            </template>
            <n-space vertical :size="8">
              <n-text strong>{{ currentGym.name }}</n-text>
              <n-text depth="2" size="small">{{ currentGym.address }}</n-text>
              <n-flex align="center" :size="12">
                <n-tag type="info" size="small">{{ getGymCategory(currentGym.type) }}</n-tag>
                <n-text depth="3" size="small">距离: {{ currentGym.distance }}m</n-text>
              </n-flex>
            </n-space>
          </n-card>

          <!-- 预约类型选择 -->
          <div>
            <n-h4>预约类型</n-h4>
            <n-radio-group
                v-model:value="reservationForm.reservationType"
                @update:value="onReservationTypeChange"
            >
              <n-space>
                <n-radio
                    :value="1"
                    :disabled="getUser().role === 2"
                >
                  健身场馆预约
                </n-radio>
                <n-radio
                    :value="2"
                    :disabled="getUser().role === 1"
                >
                  健身教练场地预约
                </n-radio>
              </n-space>
            </n-radio-group>

            <!-- 预约类型提示 -->
            <n-alert
                v-if="getUser().role === 2"
                type="info"
                style="margin-top: 8px;"
                size="small"
            >
              作为健身教练，您只能进行场地预约
            </n-alert>
            <n-alert
                v-else-if="getUser().role === 1"
                type="info"
                style="margin-top: 8px;"
                size="small"
            >
              作为健身爱好者，建议选择健身场馆预约
            </n-alert>
          </div>

          <!-- 预约日期 -->
          <div>
            <n-h4>预约日期</n-h4>
            <n-date-picker
                v-model:value="reservationForm.reservationDate"
                type="date"
                :is-date-disabled="isDateDisabled"
                style="width: 100%;"
                placeholder="请选择预约日期"
                @update:value="loadAvailableSlots"
            />
          </div>

          <!-- 预约时间段 -->
          <div>
            <n-h4>预约时间段</n-h4>
            <n-spin :show="loadingSlots">
              <div v-if="availableSlots.length > 0">
                <n-radio-group v-model:value="reservationForm.timeSlot">
                  <n-grid :cols="3" :x-gap="12" :y-gap="12">
                    <n-grid-item v-for="slot in availableSlots" :key="slot.timeSlot">
                      <n-card
                          size="small"
                          :class="{
                          'time-slot-card': true,
                          'time-slot-selected': reservationForm.timeSlot === slot.timeSlot,
                          'time-slot-full': slot.available <= 0
                        }"
                          @click="() => slot.available > 0 && (reservationForm.timeSlot = slot.timeSlot)"
                          style="cursor: pointer;"
                      >
                        <n-radio :value="slot.timeSlot" :disabled="slot.available <= 0">
                          <n-space vertical :size="4" align="center">
                            <n-text strong>{{ slot.timeSlot }}</n-text>
                            <n-text
                                size="small"
                                :type="slot.available > 0 ? 'success' : 'error'"
                            >
                              {{ slot.available > 0 ? `剩余${slot.available}位` : '已满' }}
                            </n-text>
                          </n-space>
                        </n-radio>
                      </n-card>
                    </n-grid-item>
                  </n-grid>
                </n-radio-group>
              </div>
              <n-empty v-else-if="reservationForm.reservationDate && !loadingSlots"
                       description="该日期暂无可用时间段" size="small" />
              <n-text v-else depth="3" size="small">请先选择预约日期</n-text>
            </n-spin>
          </div>

          <!-- 教练场地预约额外字段 -->
          <div v-if="reservationForm.reservationType === 2">
            <n-h4>预约区域类型</n-h4>
            <n-select
                v-model:value="reservationForm.areaType"
                placeholder="请选择预约区域类型"
                :options="[
                { label: '力量训练区', value: '力量训练区' },
                { label: '有氧训练区', value: '有氧训练区' },
                { label: '功能训练区', value: '功能训练区' },
                { label: '瑜伽室', value: '瑜伽室' },
                { label: '动感单车房', value: '动感单车房' },
                { label: '操课房', value: '操课房' }
              ]"
            />
          </div>

          <div v-if="reservationForm.reservationType === 2">
            <n-h4>课程描述</n-h4>
            <n-input
                v-model:value="reservationForm.description"
                type="textarea"
                placeholder="请简要描述您的课程内容、时长等信息（选填）"
                :autosize="{ minRows: 3, maxRows: 5 }"
            />
          </div>
        </n-space>
      </n-scrollbar>

      <template #action>
        <n-space justify="end">
          <n-button @click="showReservationModal = false">取消</n-button>
          <n-button
              type="primary"
              :loading="reserving"
              :disabled="!reservationForm.reservationDate || !reservationForm.timeSlot"
              @click="handleConfirmReservation"
          >
            确认预约
          </n-button>
        </n-space>
      </template>
    </n-modal>

    <!-- 场馆认领模态框 -->
    <n-modal
        v-model:show="showClaimModal"
        :mask-closable="false"
        preset="dialog"
        title="认领场馆"
        style="width: 500px;"
    >
      <n-form
          ref="claimFormRef"
          :model="claimForm"
          :rules="claimRules"
          label-placement="left"
          label-width="100px"
      >
        <n-form-item label="场馆名称">
          <n-input :value="currentGym?.name" readonly />
        </n-form-item>
        <n-form-item label="认领人姓名" path="claimantName">
          <n-input v-model:value="claimForm.claimantName" placeholder="请输入您的真实姓名" />
        </n-form-item>
        <n-form-item label="认领邮箱" path="email">
          <n-input v-model:value="claimForm.email" placeholder="请输入邮箱地址" />
        </n-form-item>
        <n-form-item label="邮箱验证码" path="verificationCode">
          <n-space :wrap="false">
            <n-input
                v-model:value="claimForm.verificationCode"
                placeholder="请输入验证码"
                style="flex: 1;"
            />
            <n-button
                :disabled="!claimForm.email || emailCountdown > 0"
                @click="sendVerificationCode"
                :loading="sendingCode"
            >
              {{ emailCountdown > 0 ? `${emailCountdown}秒后重发` : '发送验证码' }}
            </n-button>
          </n-space>
        </n-form-item>
        <n-form-item label="认领说明" path="claimDescription">
          <n-input
              v-model:value="claimForm.claimDescription"
              type="textarea"
              placeholder="请简要说明您与此场馆的关系（如：场馆经营者、管理员等）"
              :autosize="{ minRows: 3, maxRows: 5 }"
          />
        </n-form-item>
      </n-form>
      <template #action>
        <n-space>
          <n-button @click="showClaimModal = false">取消</n-button>
          <n-button type="primary" @click="handleClaimSubmit" :loading="claiming">
            确认认领
          </n-button>
        </n-space>
      </template>
    </n-modal>
  </div>
</template>

<script setup>
import { ref, computed, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { useMessage } from 'naive-ui'
import http from '../../utils/http.js'
import CommonHeader from '../../components/CommonHeader.vue'
import { LocationOutline, Call, Star, Calendar, BusinessOutline, PersonOutline, Settings } from '@vicons/ionicons5'
import qs from "qs";

const router = useRouter()
const message = useMessage()
const BASE_URL = window.BASE_URL

// 基础数据
const currentCategory = ref('all')
const gymList = ref([])
const showDetailModal = ref(false)
const showReservationModal = ref(false)
const currentGym = ref(null)
const reserving = ref(false)

// 认领相关数据
const showClaimModal = ref(false)
const claiming = ref(false)
const sendingCode = ref(false)
const emailCountdown = ref(0)
const claimFormRef = ref(null)
const claimForm = ref({
  gymId: null,
  userId: null,
  email: '',
  verificationCode: '',
  claimantName: '',
  claimDescription: ''
})

// 认领表单验证规则
const claimRules = {
  claimantName: [
    { required: true, message: '请输入认领人姓名', trigger: 'blur' }
  ],
  email: [
    { required: true, message: '请输入邮箱地址', trigger: 'blur' },
    { type: 'email', message: '请输入正确的邮箱格式', trigger: 'blur' }
  ],
  verificationCode: [
    { required: true, message: '请输入验证码', trigger: 'blur' },
    { len: 6, message: '验证码为6位数字', trigger: 'blur' }
  ],
  claimDescription: [
    { required: true, message: '请输入认领说明', trigger: 'blur' }
  ]
}

// 根据场馆类型定义器械模板
const equipmentTemplates = {
  '健身房': [
    { id: 1, name: '跑步机', status: '可用', description: '专业有氧训练设备', usageCount: 25, brand: '优质品牌' },
    { id: 2, name: '哑铃组', status: '可用', description: '5-50kg全套哑铃', usageCount: 18, brand: '优质品牌' },
    { id: 3, name: '史密斯机', status: '可用', description: '多功能力量训练器械', usageCount: 12, brand: '优质品牌' },
    { id: 4, name: '椭圆机', status: '可用', description: '低冲击有氧训练', usageCount: 15, brand: '优质品牌' },
    { id: 5, name: '龙门架', status: '可用', description: '多功能拉力训练', usageCount: 20, brand: '优质品牌' },
    { id: 6, name: '动感单车', status: '可用', description: '团体有氧训练设备', usageCount: 30, brand: '优质品牌' }
  ],
  '瑜伽馆': [
    { id: 1, name: '瑜伽垫', status: '可用', description: '专业瑜伽练习垫', usageCount: 50, brand: '优质品牌' },
    { id: 2, name: '瑜伽球', status: '可用', description: '辅助训练器材', usageCount: 20, brand: '优质品牌' },
    { id: 3, name: '瑜伽砖', status: '可用', description: '姿势辅助工具', usageCount: 30, brand: '优质品牌' },
    { id: 4, name: '拉力带', status: '可用', description: '阻力训练器材', usageCount: 25, brand: '优质品牌' }
  ],
  '游泳馆': [
    { id: 1, name: '标准泳道', status: '可用', description: '50米标准游泳池', usageCount: 100, brand: '专业设施' },
    { id: 2, name: '儿童池', status: '可用', description: '浅水区域适合儿童', usageCount: 40, brand: '专业设施' },
    { id: 3, name: '跳台', status: '可用', description: '专业跳水设施', usageCount: 15, brand: '专业设施' },
    { id: 4, name: '水上器械', status: '可用', description: '浮板、泳圈等辅助设备', usageCount: 60, brand: '优质品牌' }
  ],
  '私教工作室': [
    { id: 1, name: '自由重量', status: '可用', description: '哑铃、杠铃等器械', usageCount: 35, brand: '优质品牌' },
    { id: 2, name: '功能性训练器', status: '可用', description: 'TRX、壶铃等', usageCount: 28, brand: '优质品牌' },
    { id: 3, name: '有氧器械', status: '可用', description: '小型有氧训练设备', usageCount: 20, brand: '优质品牌' },
    { id: 4, name: '康复器材', status: '可用', description: '物理治疗辅助设备', usageCount: 15, brand: '专业品牌' }
  ],
  '拳击馆': [
    { id: 1, name: '沙袋', status: '可用', description: '专业训练沙袋', usageCount: 40, brand: '优质品牌' },
    { id: 2, name: '拳击台', status: '可用', description: '标准比赛拳击台', usageCount: 25, brand: '专业设施' },
    { id: 3, name: '速度球', status: '可用', description: '反应训练器材', usageCount: 30, brand: '优质品牌' },
    { id: 4, name: '护具', status: '可用', description: '头盔、手套等防护装备', usageCount: 50, brand: '专业品牌' }
  ]
}

// 计算当前场馆的器械信息
const currentGymEquipments = computed(() => {
  if (!currentGym.value) return []

  const gymCategory = getGymCategory(currentGym.value.type)

  // 首先尝试从API获取真实数据（这里可以添加API调用）
  // 如果没有真实数据，使用模板数据
  return equipmentTemplates[gymCategory] || []
})

// 场馆分类数据
const categories = ref([
  { key: 'all', label: '全部', count: 0 },
  { key: '健身中心', label: '健身房', count: 0 },
  { key: '瑜伽', label: '瑜伽馆', count: 0 },
  { key: '游泳', label: '游泳馆', count: 0 },
  { key: '私教', label: '私教工作室', count: 0 },
  { key: '拳击', label: '拳击馆', count: 0 }
])

// 器械设施相关数据
const gymEquipments = ref([
  {
    id: 1,
    name: '跑步机',
    status: '可用',
    description: '专业有氧训练设备',
    usageCount: 25,
    brand: '美国赛乐'
  },
  {
    id: 2,
    name: '哑铃组',
    status: '可用',
    description: '5-50kg全套哑铃',
    usageCount: 18,
    brand: '德国凯格'
  },
  {
    id: 3,
    name: '史密斯机',
    status: '维护中',
    description: '多功能力量训练器械',
    usageCount: 12,
    brand: '美国力健'
  },
  {
    id: 4,
    name: '椭圆机',
    status: '可用',
    description: '低冲击有氧训练',
    usageCount: 15,
    brand: '诺德克'
  },
  {
    id: 5,
    name: '龙门架',
    status: '可用',
    description: '多功能拉力训练',
    usageCount: 20,
    brand: '必确'
  },
  {
    id: 6,
    name: '动感单车',
    status: '可用',
    description: '团体有氧训练设备',
    usageCount: 30,
    brand: 'Spinning'
  }
])

// 页面加载时初始化数据
onMounted(async () => {
  console.log('GymView页面加载，开始初始化数据...')

  // 优先从后端API获取最新的场馆数据
  try {
    await refreshGymData()
  } catch (error) {
    console.error('从API获取场馆数据失败，尝试使用localStorage数据:', error)

    // 如果API调用失败，则回退到localStorage数据
    const storedGyms = localStorage.getItem('nearbyGyms')
    if (storedGyms) {
      gymList.value = JSON.parse(storedGyms)
      console.log('已加载localStorage中的场馆数据，数量:', gymList.value.length)
    } else {
      console.log('localStorage中也没有数据，使用模拟数据')
      // 如果没有存储数据，添加一些模拟数据作为示例
      gymList.value = [
        {
          "id": "B0JDORBMD1",
          "name": "这里健身",
          "type": "体育休闲服务;运动场馆;健身中心",
          "location": [102.77987, 25.034191],
          "address": "保利城·世纪名汇商业中心1栋207",
          "tel": "0871-62666682",
          "distance": 1251,
          "shopinfo": "1",
          "website": "",
          "pcode": "530000",
          "citycode": "0871",
          "adcode": "530111",
          "postcode": "",
          "pname": "云南省",
          "cityname": "昆明市",
          "adname": "官渡区",
          "email": "",
          "photos": [
            {
              "title": "",
              "url": "http://store.is.autonavi.com/showpic/7723d09bc96cc90d3c05e555bc53f9df"
            },
            {
              "title": "",
              "url": "http://store.is.autonavi.com/showpic/e512833a42f3f0002be16f05e813936e"
            }
          ],
          "entr_location": [102.780543, 25.034097],
          "exit_location": null,
          "groupbuy": false,
          "discount": false,
          "indoor_map": false,
          "rating": "4.1",
          "_idx": 0,
          "index": 0
        },
        {
          "id": "B0K1GS0AG6",
          "name": "形乐健游泳健身馆(金马店)",
          "type": "体育休闲服务;运动场馆;健身中心",
          "location": [102.755096, 25.032114],
          "address": "丽豪喜庭酒店一楼",
          "tel": "18388149128",
          "distance": 2664,
          "shopinfo": "1",
          "website": "",
          "pcode": "530000",
          "citycode": "0871",
          "adcode": "530111",
          "postcode": "",
          "pname": "云南省",
          "cityname": "昆明市",
          "adname": "官渡区",
          "email": "",
          "photos": [
            {
              "title": "",
              "url": "http://store.is.autonavi.com/showpic/2c092cd1cb253c07902aff594ff3834f"
            }
          ],
          "entr_location": null,
          "exit_location": null,
          "groupbuy": false,
          "discount": false,
          "indoor_map": false,
          "rating": "4.4",
          "_idx": 1,
          "index": 1
        },      {
          "id": "B0H1PCS4TU",
          "name": "毅力健身",
          "type": "体育休闲服务;运动场馆;健身中心",
          "location": [102.782177, 24.998381],
          "address": "东城国嘉仕苑C-62",
          "tel": "15887222863",
          "distance": 2748,
          "shopinfo": "1",
          "website": "",
          "pcode": "530000",
          "citycode": "0871",
          "adcode": "530111",
          "postcode": "",
          "pname": "云南省",
          "cityname": "昆明市",
          "adname": "官渡区",
          "email": "",
          "photos": [
            {
              "title": "",
              "url": "http://store.is.autonavi.com/showpic/fdb65546b26962a34419a8567ac3a2b5"
            },
            {
              "title": "",
              "url": "http://store.is.autonavi.com/showpic/e606490e3214171b7544387098443638"
            },
            {
              "title": "",
              "url": "http://store.is.autonavi.com/showpic/469c3074928a6d9746750c6e9140b46d"
            }
          ],
          "entr_location": [102.782279, 24.998446],
          "exit_location": null,
          "groupbuy": false,
          "discount": false,
          "indoor_map": false,
          "rating": "4.0",
          "_idx": 2,
          "index": 2
        },
        {
          "id": "B0JGXC1PET",
          "name": "静心瑜伽工作室",
          "type": "体育休闲服务;瑜伽馆;瑜伽工作室",
          "location": [102.781191, 25.049575],
          "address": "美的顺城府G3栋四楼",
          "tel": "15912104960",
          "distance": 2968,
          "shopinfo": "1",
          "website": "",
          "pcode": "530000",
          "citycode": "0871",
          "adcode": "530103",
          "postcode": "",
          "pname": "云南省",
          "cityname": "昆明市",
          "adname": "盘龙区",
          "email": "",
          "photos": [
            {
              "title": "",
              "url": "http://aos-cdn-image.amap.com/sns/ugccomment/e80e9820-80fb-4a93-9afe-00b5a7f2a8de.jpg"
            }
          ],
          "entr_location": [102.781095, 25.04979],
          "exit_location": null,
          "groupbuy": false,
          "discount": false,
          "indoor_map": false,
          "rating": "4.3",
          "_idx": 3,
          "index": 3
        },
        {
          "id": "B0SONG1234",
          "name": "SONG私教工作室",
          "type": "体育休闲服务;私教工作室;健身工作室",
          "location": [102.781828, 25.047804],
          "address": "金瓦路碧桂园凤凰湾4栋102室",
          "tel": "13888387957",
          "distance": 2776,
          "shopinfo": "1",
          "website": "",
          "pcode": "530000",
          "citycode": "0871",
          "adcode": "530103",
          "postcode": "",
          "pname": "云南省",
          "cityname": "昆明市",
          "adname": "盘龙区",
          "email": "",
          "photos": [
            {
              "title": "",
              "url": "http://store.is.autonavi.com/showpic/e6d0bd78b839c622305695bfcb82796b"
            }
          ],
          "entr_location": null,
          "exit_location": null,
          "groupbuy": false,
          "discount": false,
          "indoor_map": false,
          "rating": "4.1",
          "_idx": 4,
          "index": 4
        },
        {
          "id": "B0BOXING888",
          "name": "力量拳击俱乐部",
          "type": "体育休闲服务;拳击馆;搏击俱乐部",
          "location": [102.765817, 25.045452],
          "address": "诚信路金香巷78号",
          "tel": "18788553086",
          "distance": 2859,
          "shopinfo": "1",
          "website": "",
          "pcode": "530000",
          "citycode": "0871",
          "adcode": "530103",
          "postcode": "",
          "pname": "云南省",
          "cityname": "昆明市",
          "adname": "盘龙区",
          "email": "",
          "photos": [
            {
              "title": "",
              "url": "http://store.is.autonavi.com/showpic/750a054ef4cbeb64c60d0c5bfbaa9a1f"
            }
          ],
          "entr_location": [102.765748, 25.045257],
          "exit_location": null,
          "groupbuy": false,
          "discount": false,
          "indoor_map": false,        "rating": "4.2",
          "_idx": 5,
          "index": 5
        }
      ]
    }
  }
})

// 场馆分类过滤
const filteredGyms = computed(() => {
  if (currentCategory.value === 'all') {
    return gymList.value
  }
  return gymList.value.filter(gym =>
      gym.type.includes(currentCategory.value)
  )
})

// 获取场馆分类
const getGymCategory = (type) => {
  if (type.includes('健身中心') || type.includes('健身房')) return '健身房'
  if (type.includes('瑜伽')) return '瑜伽馆'
  if (type.includes('游泳')) return '游泳馆'
  if (type.includes('私教') || type.includes('工作室')) return '私教工作室'
  if (type.includes('拳击') || type.includes('搏击') || type.includes('格斗')) return '拳击馆'
  return '健身场所'
}

// 智能生成场馆介绍
const generateGymDescription = (gym) => {
  if (gym.description && gym.description !== '暂无详细介绍') {
    return gym.description
  }

  const category = getGymCategory(gym.type)
  const name = gym.name
  const district = gym.adname || '当地'

  const descriptions = {
    '健身房': [
      `${name}位于${district}，是一家专业的健身中心。`,
      '配备先进的健身器械，包括有氧设备、力量训练器械等。',
      '提供专业的健身指导和个性化训练方案。',
      '营造舒适的运动环境，助您达成健身目标。'
    ],
    '瑜伽馆': [
      `${name}是${district}的专业瑜伽练习场所。`,
      '提供多种瑜伽课程，适合不同水平的练习者。',
      '宁静舒适的练习环境，专业的瑜伽导师指导。',
      '帮助您在身心平衡中获得健康与宁静。'
    ],
    '游泳馆': [
      `${name}拥有标准的游泳设施，位于${district}。`,
      '水质清洁，温度适宜，适合各年龄段游泳爱好者。',
      '提供游泳培训、水中健身等多项服务。',
      '是您进行水上运动和健身的理想选择。'
    ],
    '私教工作室': [
      `${name}是${district}的专业私人教练工作室。`,
      '提供一对一个性化训练指导。',
      '小班制教学，针对性强，效果显著。',
      '专业教练团队为您制定专属健身计划。'
    ],
    '拳击馆': [
      `${name}是${district}的专业拳击训练场所。`,
      '配备专业拳击器材，提供拳击技能培训。',
      '适合初学者和进阶者的不同训练需求。',
      '在挥拳中释放压力，锻炼身体协调性。'
    ]
  }

  const defaultDesc = [
    `${name}是位于${district}的专业健身场所。`,
    '提供优质的运动环境和专业的服务。',
    '欢迎运动爱好者前来体验。'
  ]

  const categoryDesc = descriptions[category] || defaultDesc
  return categoryDesc.join(' ')
}

// 处理场馆卡片点击
const handleGymClick = (gym) => {
  currentGym.value = gym
  showDetailModal.value = true
}

// 预约相关数据
const reservationForm = ref({
  reservationType: 1, // 默认为健身场馆预约
  gymId: null,
  reservationDate: null,
  timeSlot: null,
  areaType: null,
  description: ''
})
const availableSlots = ref([])
const loadingSlots = ref(false)

// 处理预约
const handleReservation = () => {
  // 检查用户是否已登录
  if (!isUserLoggedIn()) {
    message.warning('请先登录后再进行预约')
    router.push('/login')
    return
  }

  // 检查场馆是否已被认领
  if (!isGymClaimed(currentGym.value)) {
    message.warning('该场馆尚未被认领，暂时无法预约。场馆需要先由管理员认领后才能接受预约。')
    return
  }

  // 检查场馆运营状态
  if (currentGym.value.operatingStatus === 'closed') {
    message.warning('该场馆暂停营业，无法预约')
    return
  }

  // 检查场馆状态是否为激活状态
  if (currentGym.value.status === 'inactive') {
    message.warning('该场馆当前暂停营业，暂时无法接受预约')
    return
  }

  // 根据用户角色设置默认预约类型
  const userInfo = getUser()
  if (userInfo.role === 2) {
    reservationForm.value.reservationType = 2 // 健身教练默认场地预约
  } else {
    reservationForm.value.reservationType = 1 // 健身爱好者默认场馆预约
  }

  // 设置当前场馆ID
  reservationForm.value.gymId = currentGym.value.id || currentGym.value.gymId

  // 重置其他字段
  reservationForm.value.reservationDate = null
  reservationForm.value.timeSlot = null
  reservationForm.value.areaType = null
  reservationForm.value.description = ''

  // 清空可用时间段
  availableSlots.value = []

  showReservationModal.value = true
}

// 加载可用时间段
const loadAvailableSlots = async () => {
  if (!reservationForm.value.gymId || !reservationForm.value.reservationDate) {
    return
  }

  loadingSlots.value = true
  try {
    const dateStr = new Date(reservationForm.value.reservationDate).toISOString().split('T')[0]

    const response = await http.get('/v1/reservation/available-slots', {
      params: {
        gymId: reservationForm.value.gymId,
        date: dateStr
      }
    })
    if (response.data.code === 2000) {
      // 后端返回的是简单字符串数组，需要转换为前端期望的对象格式
      const rawSlots = response.data.data || []
      availableSlots.value = rawSlots.map(timeSlot => ({
        timeSlot: timeSlot,
        available: 10, // 默认可用容量，可以根据实际需求调整
        total: 10,     // 默认总容量
        price: 50      // 默认价格，可以根据实际需求调整
      }))
      console.log('可用时间段:', availableSlots.value)
    } else {
      message.error(response.data.msg || '获取可用时间段失败')
    }
  } catch (error) {
    console.error('加载可用时间段失败:', error)
    message.error('加载可用时间段失败')
  } finally {
    loadingSlots.value = false
  }
}

// 预约类型改变处理
const onReservationTypeChange = () => {
  // 清空相关字段
  reservationForm.value.areaType = null
  reservationForm.value.description = ''
}

// 禁用过去的日期
const isDateDisabled = (ts) => {
  const today = new Date()
  today.setHours(0, 0, 0, 0)
  return ts < today.getTime()
}

// 确认预约
const handleConfirmReservation = async () => {
  // 表单验证
  if (!reservationForm.value.reservationDate) {
    message.warning('请选择预约日期')
    return
  }

  if (!reservationForm.value.timeSlot) {
    message.warning('请选择预约时间段')
    return
  }

  // 如果是教练场地预约，需要选择区域类型
  if (reservationForm.value.reservationType === 2 && !reservationForm.value.areaType) {
    message.warning('请选择预约区域类型')
    return
  }

  // 检查选中的时间段是否还有剩余容量
  const selectedSlot = availableSlots.value.find(slot => slot.timeSlot === reservationForm.value.timeSlot)
  if (selectedSlot && selectedSlot.available <= 0) {
    message.warning('该时间段已满，请选择其他时间段')
    return
  }

  reserving.value = true
  try {
    const reservationData = {
      reservationType: reservationForm.value.reservationType,
      gymId: reservationForm.value.gymId,
      reservationDate: new Date(reservationForm.value.reservationDate).toISOString().split('T')[0],
      timeSlot: reservationForm.value.timeSlot
    }

    // 如果是教练场地预约，添加额外字段
    if (reservationForm.value.reservationType === 2) {
      reservationData.areaType = reservationForm.value.areaType
      reservationData.description = reservationForm.value.description
    }    console.log('提交预约数据:', reservationData)

    const response = await http.post('/v1/reservation/create', reservationData)

    if (response.data.code === 2000) {
      const reservationResult = response.data.data
      message.success('预约提交成功！正在为您创建与场馆管理员的聊天会话...')

      showReservationModal.value = false

      // 重置表单
      reservationForm.value = {
        reservationType: 1,
        gymId: null,
        reservationDate: null,
        timeSlot: null,
        areaType: null,
        description: ''
      }
      availableSlots.value = []

      // 直接跳转到聊天页面，无需询问
      if (reservationResult?.chatSessionId) {
        // 跳转到聊天页面，并传递预约信息用于发送初始消息
        router.push({
          path: '/chat',
          query: {
            sessionId: reservationResult.chatSessionId,
            type: 'reservation',
            reservationId: reservationResult.id,
            gymName: currentGym.value.name,
            reservationType: reservationForm.value.reservationType === 1 ? '场馆预约' : '场地预约',
            reservationDate: reservationData.reservationDate,
            timeSlot: reservationData.timeSlot
          }
        })
      } else {
        // 如果没有聊天会话ID，说明后端没有创建聊天会话，跳转到消息页面
        message.info('预约成功！正在跳转到消息页面...')
        setTimeout(() => {
          router.push('/chat')
        }, 1500)
      }
    } else {
      message.error(response.data.msg || '预约失败')
    }
  } catch (error) {
    console.error('预约失败:', error)
    message.error(error.message || '预约失败，请稍后重试')
  } finally {
    reserving.value = false
  }
}

// 联系场馆
const handleCallGym = () => {
  if (currentGym.value?.tel) {
    message.info(`联系电话: ${currentGym.value.tel}`)
  }
}

// 跳转到地图页面
const handleGoToMap = () => {
  router.push('/map')
}

// 发送邮箱验证码
const sendVerificationCode = async () => {
  if (!claimForm.value.email) {
    message.warning('请先输入邮箱地址')
    return
  }

  // 验证邮箱格式
  const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/
  if (!emailRegex.test(claimForm.value.email)) {
    message.warning('请输入正确的邮箱格式')
    return
  }
  sendingCode.value = true
  try {
    console.log('发送验证码到邮箱:', claimForm.value.email)
    // 使用http发送请求，使用正确的后端API路径
    const response = await http.post(`/v1/gym/sendVerificationCode`, qs.stringify({
      email: claimForm.value.email
    }), {
      headers: {
        'Content-Type': 'application/x-www-form-urlencoded'
      }
    })

    console.log('发送验证码响应:', response.data)

    if (response.data.code === 2000) {
      message.success('验证码已发送到您的邮箱，请查收（可能需要1-2分钟到达）')
      // 开始倒计时
      emailCountdown.value = 60
      const timer = setInterval(() => {
        emailCountdown.value--
        if (emailCountdown.value <= 0) {
          clearInterval(timer)
        }
      }, 1000)
    } else {
      message.error(response.data.msg || '发送验证码失败')
    }
  } catch (error) {
    console.error('发送验证码失败:', error)
    message.error('发送验证码失败，请稍后重试')
  } finally {
    sendingCode.value = false
  }
}

// 提交认领申请
const handleClaimSubmit = async () => {
  // 表单验证
  try {
    await claimFormRef.value?.validate()
  } catch (error) {
    message.warning('请检查表单填写是否完整')
    return
  }

  // 检查用户登录状态和token
  const userInfo = getUser();
  console.log("gym里的用户信息:", userInfo);
  if (!userInfo || !userInfo.tokenInfo) {
    message.warning('登录状态已过期，请重新登录')
    router.push('/login')
    return
  }

  claiming.value = true
  try {
    // 准备认领数据
    const claimData = {
      gymId: currentGym.value.id || currentGym.value.gymId,  // 兼容不同的属性名
      email: claimForm.value.email,
      verificationCode: claimForm.value.verificationCode,
      claimantName: claimForm.value.claimantName,
      claimDescription: claimForm.value.claimDescription
    }

    console.log('提交认领数据:', claimData)
    // 调用认领API - 使用配置好的http工具，自动包含token认证信息
    const response = await http.post(`/v1/gym/claim`, claimData)
    if (response.data.code === 2000) {
      message.success('场馆认领成功！您现在可以在个人中心管理此场馆')
      showClaimModal.value = false
      // 重置表单
      claimForm.value = {
        gymId: null,
        userId: null,
        email: '',
        verificationCode: '',
        claimantName: '',
        claimDescription: ''
      }

      // 立即刷新场馆数据以显示认领状态
      await refreshGymData()

      // 更新当前场馆的认领状态和员工信息
      if (currentGym.value) {
        await updateCurrentGymClaimStatus()
      }
    } else {
      message.error(response.data.msg || '认领失败')
    }
  } catch (error) {
    console.error('认领失败:', error)
    if (error.response?.status === 401) {
      message.error('登录状态已过期，请重新登录')
      router.push('/login')
    } else {
      message.error('认领失败，请稍后重试')
    }
  } finally {
    claiming.value = false
  }
}

// 获取当前用户ID（需要从登录状态获取）
const getCurrentUserId = () => {
  // 从localStorage获取当前登录用户的ID
  try {
    const userInfo = JSON.parse(localStorage.getItem('user') || '{}')
    console.log('获取当前用户信息:', userInfo)
    return userInfo.userId || null
  } catch (error) {
    console.error('解析用户信息失败:', error)
    return null
  }
}

// 判断当前用户是否为场馆所有者
const isGymOwner = (gym) => {
  if (!gym) return false

  try {
    const currentUser = JSON.parse(localStorage.getItem('user') || '{}')
    if (!currentUser.userId) return false

    // 检查场馆是否被当前用户认领
    return gym.userId && gym.userId === currentUser.userId
  } catch (error) {
    console.error('检查场馆所有权失败:', error)
    return false
  }
}

// 跳转到场馆管理中心
const goToManagementCenter = () => {
  router.push('/gym/management')
}

// 检查用户是否已登录
const isUserLoggedIn = () => {
  try {
    const userInfo = JSON.parse(localStorage.getItem('user') || '{}')
    return userInfo.userId && userInfo.tokenInfo
  } catch (error) {
    console.error('检查登录状态失败:', error)
    return false
  }
}

// 判断用户是否为场馆人员
const isGymStaff = computed(() => {
  try {
    const userInfo = JSON.parse(localStorage.getItem('user') || '{}')
    return userInfo.role === 4
  } catch (error) {
    console.error('解析用户信息失败:', error)
    return false
  }
})

// 判断场馆是否已被认领
const isGymClaimed = (gym) => {
  if (!gym) return false

  // 检查场馆是否有认领状态信息
  // 从后端API返回的数据中，已认领的场馆会有userId和相应的status
  return (gym.userId && gym.status && gym.status !== 'unclaimed') ||
      gym.claimedStaff ||  // 如果有认领员工信息则表示已认领
      gym.status === 'pending' ||  // 待审核状态
      gym.status === 'approved'    // 已通过审核状态
}

// 打开认领模态框
const openClaimModal = () => {
  // 检查用户是否已登录
  if (!isUserLoggedIn()) {
    message.warning('请先登录后再认领场馆')
    // 跳转到登录页面，登录后返回当前页面
    const currentPath = router.currentRoute.value.fullPath
    router.push(`/login?redirect=${encodeURIComponent(currentPath)}`)
    return
  }

  const userId = getCurrentUserId()
  if (!userId) {
    message.warning('获取用户信息失败，请重新登录')
    router.push('/login')
    return
  }

  // 检查用户角色是否为场馆人员
  try {
    const userInfo = JSON.parse(localStorage.getItem('user') || '{}')
    if (userInfo.role !== 4) {
      message.warning('只有场馆人员才能认领场馆')
      return
    }
  } catch (error) {
    console.error('检查用户角色失败:', error)
    message.error('用户信息异常，请重新登录')
    return
  }
  // 设置当前场馆ID和用户ID
  claimForm.value.gymId = currentGym.value.id || currentGym.value.gymId
  claimForm.value.userId = userId
  showClaimModal.value = true
}

// 状态格式化方法
const getStatusType = (status) => {
  switch (status) {
    case 'closed':
      return 'warning'
    case 'open':
      return 'success'
    case 'rejected':
      return 'error'
    case 'unclaimed':
      return 'info'
    default:
      return 'default'
  }
}

const getStatusText = (status) => {
  switch (status) {
    case 'closed':
      return '暂停营业'
    case 'open':
      return '正常营业'
    case 'rejected':
      return '认领被拒'
    case 'unclaimed':
      return '未认领'
    default:
      return '未知状态'
  }
}

const formatDate = (dateString) => {
  if (!dateString) return ''
  return new Date(dateString).toLocaleString('zh-CN')
}

// 获取用户信息的通用函数
const getUser = () => {
  try {
    return JSON.parse(localStorage.getItem('user') || '{}')
  } catch (error) {
    console.error('解析用户信息失败:', error)
    return {}
  }
}

// 刷新场馆数据
const refreshGymData = async () => {
  try {
    console.log('开始刷新场馆数据...')
    // 1. 获取API中的已认领场馆数据
    const response = await http.get(`/v1/gym/getAllPOIGyms`)
    let claimedGyms = []

    if (response.data.code === 2000 && response.data.data) {
      // 过滤出已认领的场馆（有userId的）
      claimedGyms = response.data.data.filter(gym => gym.userId != null)
      console.log('已认领场馆数量:', claimedGyms.length)
      console.log('已认领场馆数据示例:', claimedGyms[0])
    }

    // 2. 获取localStorage中的POI原始数据
    const storedGyms = JSON.parse(localStorage.getItem('nearbyGyms') || '[]')
    console.log('本地存储的POI场馆数量:', storedGyms.length)
    console.log('POI场馆数据示例:', storedGyms[0])

    // 如果localStorage没有数据，尝试使用示例数据
    if (storedGyms.length === 0) {
      console.log('localStorage无数据，使用示例POI数据')
      const mockPOIData = [
        {
          "id": "B0K1GS0AG6",
          "name": "形乐健游泳健身馆(金马店)",
          "type": "体育休闲服务;运动场馆;健身中心",
          "location": [102.755096, 25.032114],
          "address": "丽豪喜庭酒店一楼",
          "tel": "18388149128",
          "distance": 759,
          "adname": "官渡区",
          "photos": [
            {
              "title": "",
              "url": "http://store.is.autonavi.com/showpic/2c092cd1cb253c07902aff594ff3834f"
            }
          ],
          "rating": "4.4"
        },
        {
          "id": "B0K0K73RT7",
          "name": "菲尼克斯游泳健身",
          "type": "体育休闲服务;运动场馆;健身中心|体育休闲服务;运动场馆;游泳馆",
          "location": [102.765817, 25.045452],
          "address": "诚信路金香巷78号",
          "tel": "18788553086",
          "distance": 1980,
          "adname": "官渡区",
          "photos": [
            {
              "title": "",
              "url": "https://picsum.photos/400/300?random=1"
            }
          ],
          "rating": "4.2"
        }
      ]
      localStorage.setItem('nearbyGyms', JSON.stringify(mockPOIData))
      storedGyms.push(...mockPOIData)
    }
    // 3. 合并数据：优先使用已认领的场馆数据，未认领的使用POI原始数据
    const mergedGyms = []

    // 添加已认领的场馆（使用API数据，包含最新的管理信息）
    // 确保已认领场馆保留POI原始数据，特别是photos字段
    const enhancedClaimedGyms = claimedGyms.map(claimedGym => {
      // 尝试从localStorage中找到对应的POI原始数据
      const originalPOI = storedGyms.find(poi => poi.id === claimedGym.poiId || poi.id === claimedGym.id)

      if (originalPOI) {
        // 合并API数据和POI原始数据，优先保留API的管理字段，但补充POI的photos等字段
        return {
          ...originalPOI, // POI原始数据作为基础
          ...claimedGym,   // API数据覆盖
          // 确保重要的POI字段不被覆盖
          photos: originalPOI.photos || claimedGym.photos || [],
          rating: originalPOI.rating || claimedGym.rating,
          tel: originalPOI.tel || claimedGym.tel,
          adname: originalPOI.adname || claimedGym.adname,
          distance: originalPOI.distance || claimedGym.distance
        }
      }

      return claimedGym
    })

    mergedGyms.push(...enhancedClaimedGyms)

    // 添加未认领的POI场馆（使用原始POI数据，保持photos等字段）
    const claimedPoiIds = new Set(claimedGyms.map(gym => gym.poiId || gym.id))
    const unclaimedPoiGyms = storedGyms.filter(gym => !claimedPoiIds.has(gym.id))

    // 为未认领的POI场馆添加必要的字段
    const processedUnclaimedGyms = unclaimedPoiGyms.map(poiGym => ({
      ...poiGym,
      gymId: null,
      userId: null,
      status: 'unclaimed',
      isPoiSource: true,
      claimedStaff: null,
      claimedAt: null,
      // 保持POI的原始字段：photos, rating, tel, adname, distance等
    }))

    mergedGyms.push(...processedUnclaimedGyms)

    // 更新gymList
    gymList.value = mergedGyms
    console.log('场馆数据合并完成，总数量:', gymList.value.length)
    console.log('- 已认领场馆:', enhancedClaimedGyms.length)
    console.log('- 未认领POI场馆:', processedUnclaimedGyms.length)

    // 调试：检查照片数据
    const gymsWithPhotos = mergedGyms.filter(gym => gym.photos && gym.photos.length > 0)
    console.log('- 有照片的场馆:', gymsWithPhotos.length)
    if (gymsWithPhotos.length > 0) {
      console.log('照片数据示例:', gymsWithPhotos[0].photos[0])
    }

  } catch (error) {
    console.error('刷新场馆数据失败:', error)
    // 如果API失败，回退到使用localStorage数据
    const fallbackGyms = JSON.parse(localStorage.getItem('nearbyGyms') || '[]')
    if (fallbackGyms.length > 0) {
      gymList.value = fallbackGyms.map(gym => ({
        ...gym,
        status: 'unclaimed',
        isPoiSource: true
      }))
      console.log('使用本地存储的场馆数据，数量:', gymList.value.length)
    }
  }
}

// 更新当前场馆的认领状态和员工信息
const updateCurrentGymClaimStatus = async () => {
  if (!currentGym.value) return

  try {
    console.log('更新当前场馆认领状态...')

    // 在刷新后的gymList中找到当前场馆
    const updatedGym = gymList.value.find(gym =>
        gym.id === currentGym.value.id ||
        gym.gymId === currentGym.value.gymId ||
        gym.poiId === currentGym.value.id
    )

    if (updatedGym) {
      // 更新currentGym的数据
      currentGym.value = { ...currentGym.value, ...updatedGym }
      console.log('当前场馆状态已更新:', currentGym.value.status)
    } else {
      console.log('未找到匹配的场馆数据')
    }
  } catch (error) {
    console.error('更新当前场馆状态失败:', error)
  }
}
</script>

<style scoped>
.gym-container {
  max-width: 1200px;
  margin: 0 auto;
  padding: 20px;
}

.gym-tabs {
  margin-bottom: 20px;
}

.gym-grid {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(300px, 1fr));
  gap: 20px;
  padding: 20px 0;
}

.gym-card {
  transition: all 0.3s ease;
  cursor: pointer;
}

.gym-card:hover {
  transform: translateY(-4px);
  box-shadow: 0 8px 24px rgba(0, 0, 0, 0.12);
}

.gym-image-container {
  position: relative;
  height: 200px;
  margin-bottom: 16px;
}

.gym-image {
  width: 100%;
  height: 100%;
  object-fit: cover;
  border-radius: 8px;
}

.no-image {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  height: 100%;
  background-color: #f8f9fa;
  border-radius: 8px;
  gap: 8px;
}

.rating-tag {
  position: absolute;
  top: 8px;
  right: 8px;
}

.gym-info {
  padding: 0 4px;
}

.gym-name {
  font-size: 16px;
  line-height: 1.4;
  display: -webkit-box;
  -webkit-line-clamp: 1;
  line-clamp: 1;
  -webkit-box-orient: vertical;
  overflow: hidden;
}

.gym-address {
  display: flex;
  align-items: center;
  gap: 4px;
  line-height: 1.4;
  display: -webkit-box;
  -webkit-line-clamp: 2;
  line-clamp: 2;
  -webkit-box-orient: vertical;
  overflow: hidden;
}

.empty-state {
  margin: 60px 0;
}

.gym-detail-modal {
  max-height: 80vh;
}

.gym-detail {
  padding: 0 8px;
}

.gym-header {
  border-bottom: 1px solid #f0f0f0;
  padding-bottom: 16px;
}

.gym-photos .carousel-image {
  width: 100%;
  height: 300px;
  object-fit: cover;
  border-radius: 8px;
}

.contact-info,
.gym-equipments,
.reservation-section {
  border-top: 1px solid #f0f0f0;
  padding-top: 16px;
}

.section-header {
  margin-bottom: 16px;
}

/* 时间段选择样式 */
.time-slot-available {
  border: 2px solid #18a058;
  transition: all 0.3s ease;
}

.time-slot-available:hover {
  background-color: #f0f9ff;
  transform: scale(1.02);
}

.time-slot-full {
  border: 2px solid #d03050;
  opacity: 0.6;
  cursor: not-allowed !important;
}

.time-slot-selected {
  border: 2px solid #2080f0;
  background-color: #e6f4ff;
  transform: scale(1.05);
}

.time-slot-selected:hover {
  background-color: #e6f4ff;
}

/* 新的预约时间段卡片样式 */
.time-slot-card {
  transition: all 0.3s ease;
  border: 2px solid #e0e0e6;
  cursor: pointer;
}

.time-slot-card:hover {
  border-color: #2080f0;
  transform: scale(1.02);
}

.time-slot-card.time-slot-selected {
  border-color: #2080f0;
  background-color: #e6f4ff;
  transform: scale(1.05);
}

.time-slot-card.time-slot-full {
  border-color: #d03050;
  opacity: 0.6;
  cursor: not-allowed !important;
}

.time-slot-card.time-slot-full:hover {
  transform: none;
  border-color: #d03050;
}

/* 预约弹窗样式 */
.reservation-modal :deep(.n-card__content) {
  max-height: 60vh;
  overflow-y: auto;
}

/* 器械卡片样式 */
.gym-equipments .n-card {
  transition: all 0.3s ease;
}

.gym-equipments .n-card:hover {
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
  transform: translateY(-2px);
}

/* 预约表单样式优化 */
.reservation-modal .n-radio-group .n-radio {
  margin-right: 16px;
}

.reservation-modal .n-alert {
  border-radius: 6px;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .gym-container {
    padding: 10px;
  }

  .gym-grid {
    grid-template-columns: 1fr;
    gap: 16px;
  }

  .gym-detail-modal {
    width: 95% !important;
  }

  .reservation-modal {
    width: 95% !important;
  }

  .gym-photos .carousel-image {
    height: 200px;
  }
}

.gym-tabs {
  margin-bottom: 20px;
}

.gym-grid {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(300px, 1fr));
  gap: 20px;
  padding: 20px 0;
}

.gym-card {
  transition: all 0.3s ease;
  cursor: pointer;
}

.gym-card:hover {
  transform: translateY(-4px);
  box-shadow: 0 8px 24px rgba(0, 0, 0, 0.12);
}

.gym-image-container {
  position: relative;
  height: 200px;
  margin-bottom: 16px;
}

.gym-image {
  width: 100%;
  height: 100%;
  object-fit: cover;
  border-radius: 8px;
}

.no-image {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  height: 100%;
  background-color: #f8f9fa;
  border-radius: 8px;
  gap: 8px;
}

.rating-tag {
  position: absolute;
  top: 8px;
  right: 8px;
}

.gym-info {
  padding: 0 4px;
}

.gym-name {
  font-size: 16px;
  line-height: 1.4;
  display: -webkit-box;
  -webkit-line-clamp: 1;
  line-clamp: 1;
  -webkit-box-orient: vertical;
  overflow: hidden;
}

.gym-address {
  display: flex;
  align-items: center;
  gap: 4px;
  line-height: 1.4;
  display: -webkit-box;
  -webkit-line-clamp: 2;
  line-clamp: 2;
  -webkit-box-orient: vertical;
  overflow: hidden;
}

.empty-state {
  margin: 60px 0;
}

.gym-detail-modal {
  max-height: 80vh;
}

.gym-detail {
  padding: 0 8px;
}

.gym-header {
  border-bottom: 1px solid #f0f0f0;
  padding-bottom: 16px;
}

.gym-photos .carousel-image {
  width: 100%;
  height: 300px;
  object-fit: cover;
  border-radius: 8px;
}

.contact-info,
.gym-equipments,
.reservation-section {
  border-top: 1px solid #f0f0f0;
  padding-top: 16px;
}

.section-header {
  margin-bottom: 16px;
}

/* 时间段选择样式 */
.time-slot-available {
  border: 2px solid #18a058;
  transition: all 0.3s ease;
}

.time-slot-available:hover {
  background-color: #f0f9ff;
  transform: scale(1.02);
}

.time-slot-full {
  border: 2px solid #d03050;
  opacity: 0.6;
  cursor: not-allowed !important;
}

.time-slot-selected {
  border: 2px solid #2080f0;
  background-color: #e6f4ff;
  transform: scale(1.05);
}

.time-slot-selected:hover {
  background-color: #e6f4ff;
}

/* 新的预约时间段卡片样式 */
.time-slot-card {
  transition: all 0.3s ease;
  border: 2px solid #e0e0e6;
  cursor: pointer;
}

.time-slot-card:hover {
  border-color: #2080f0;
  transform: scale(1.02);
}

.time-slot-card.time-slot-selected {
  border-color: #2080f0;
  background-color: #e6f4ff;
  transform: scale(1.05);
}

.time-slot-card.time-slot-full {
  border-color: #d03050;
  opacity: 0.6;
  cursor: not-allowed !important;
}

.time-slot-card.time-slot-full:hover {
  transform: none;
  border-color: #d03050;
}

/* 预约弹窗样式 */
.reservation-modal :deep(.n-card__content) {
  max-height: 60vh;
  overflow-y: auto;
}

/* 器械卡片样式 */
.gym-equipments .n-card {
  transition: all 0.3s ease;
}

.gym-equipments .n-card:hover {
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
  transform: translateY(-2px);
}

/* 预约表单样式优化 */
.reservation-modal .n-radio-group .n-radio {
  margin-right: 16px;
}

.reservation-modal .n-alert {
  border-radius: 6px;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .gym-container {
    padding: 10px;
  }

  .gym-grid {
    grid-template-columns: 1fr;
    gap: 16px;
  }

  .gym-detail-modal {
    width: 95% !important;
  }

  .reservation-modal {
    width: 95% !important;
  }

  .gym-photos .carousel-image {
    height: 200px;
  }
}
</style>
